import re


def parse_configs(config_str):
    """解析配置字符串，返回参数字典"""
    if not config_str or not config_str.strip():
        return {}

    config_dict = {}
    # 按分号分割多个配置项
    config_items = config_str.split(';')

    for item in config_items:
        item = item.strip()
        if '=' in item:
            key, value = item.split('=', 1)  # 分割一次，防止值中有等号
            key = key.strip()
            value = value.strip()
            props_location_match = re.search(r'\[@([^\]]+)\]', key)
            if props_location_match:
                props_location = props_location_match.group(1)
            else:
                props_location = None

            # 类型转换尝试
            if value.isdigit():  # 整数
                value = int(value)
            elif value.lower() in ('true', 'false'):  # 布尔值
                value = value.lower() == 'true'
            elif value.replace('.', '', 1).isdigit():  # 浮点数
                value = float(value)

            config_dict[key] = (value, props_location)

    return config_dict


def parse_exculsion_paths(config_str):
    if not config_str:
        return {}
    level_exclusion_path_map = {}
    for item in config_str:
        level_exclusion_path_map[item["level"]] = (
            item["type"],
            item["folders"].split(",") if "folders" in item else [],
            item["files"].split(",") if "files" in item else []
        )
    return level_exclusion_path_map

def traverse_and_parse_paths(app_state_path_list, app=""):
    """遍历数据结构，解析路径配置"""
    results = {}

    for app_info in app_state_path_list:
        app_name = app_info["app"]
        if app and app_name != app:
            continue
        app_type = app_info["type"]
        app_enabled  = app_info["enabled"]

        print(f"应用: {app_name} (类型: {app_type})")

        for path_info in app_info["path_list"]:
            path = {
                "path": path_info["path"],
                "level": path_info["level"],
                "action": path_info["action"],
                # "original_configs": path_info["configs"],
                "parsed_configs": parse_configs(path_info["configs"]) if "configs" in path_info else {},
                "desc": path_info["desc"] if "desc" in path_info else "",
                "path_filters": parse_exculsion_paths(path_info["path_filters"]) if "path_filters" in path_info else []
            }

            # 解析配置
            # parsed_configs = parse_configs(configs_str)

            if app_name not in results:
                # 构建结果
                result = {
                    "app": app_name,
                    "type": app_type,
                    "enabled": app_enabled,
                    "path_list": [path]
                }
                results[app_name] = result
            else:
                results[app_name]["path_list"].append(path)

            # results.append(result)

            # 打印详细信息
            # print(f"  路径: {path}")
            # print(f"  原始配置: {configs_str}")
            # print(f"  解析后配置: {parsed_configs}")
            # if desc:
            #     print(f"  描述: {desc}")
            # print("  " + "-" * 50)

        print()  # 空行分隔不同应用

    return results